<?php

class Aes
{
    private $key;
    private $encode;
    private $method;
    private $iv;

    public function __construct($key = '', $encode = 'base64', $method = 'AES-256-ECB', $iv = null)
    {
    	$defaultKey = 'SFH26R0DTJ8DH2VP2T2V2DBZ0XLDX900';
    	
        $this->key = $key ?: $defaultKey;
        $this->encode = $encode;
        $this->method = $method;
        $this->iv = $iv;
    }

    /**
	 * 加密字符串
	 *
	 * @param string $str 字符串
	 * @return string
	 */
	public function encode($str)
	{
		try {
			$data = openssl_encrypt($str, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
			if($this->encode == "hex"){
				return bin2hex($data);
			}
			elseif($this->encode == "base64"){
				return base64_encode($data);
			}
		}
		catch (\Exception $e) {
			return false;
		}
	}
	
	/**
	 * 解密字符串
	 *
	 * @param string $str 字符串
	 * @return string
	 */
	public function decode($str)
	{
		try {
			if($this->encode == "hex"){
				$str = pack("H*", $str);
			}
			if($this->encode == "base64"){
				$str = base64_decode($str);
			}
			$data = openssl_decrypt($str, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
			return $data;
		}
		catch (\Exception $e) {
			return false;
		}
	}
}